package com.hlxt.nj.common;

import com.alibaba.fastjson.JSON;
import com.mysql.jdbc.StringUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.*;

public class JSONUtil {
    public static Map<String, Object> parseJSON2Map(String jsonStr){
    	jsonStr = jsonStr.replace("[", "");
    	jsonStr = jsonStr.replace("]", "");
        Map<String, Object> map = new HashMap<String, Object>();
        //最外层解析
        JSONObject json = JSONObject.fromObject(jsonStr);
        for(Object k : json.keySet()){
            Object v = json.get(k); 
            //如果内层还是数组的话，继续解析
            if(v instanceof JSONArray){
                List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
                Iterator<JSONObject> it = ((JSONArray)v).iterator();
                while(it.hasNext()){
                    JSONObject json2 = it.next();
                    list.add(parseJSON2Map(json2.toString()));
                }
                map.put(k.toString(), list);
            } else {
                map.put(k.toString(), v);
            }
        }
        return map;
    }
    
    
    public static Map<String, String> parseJSON2StringMap(String jsonStr){
    	Map<String, String> body = new HashMap<String, String>();
    	if(StringUtils.isNullOrEmpty(jsonStr))return body;
    	jsonStr = jsonStr.replace("[", "");
    	jsonStr = jsonStr.replace("]", "");
		JSONObject jsonObject = JSONObject.fromObject(jsonStr);
		for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
			String key = (String) iter.next();
			body.put(key, jsonObject.get(key).toString());
		}
    	return body;
    }
    
    public static String obj2JSONStr(Object obj){
		String result = "";
		JSONArray jsonArray = JSONArray.fromObject(obj);
		result = jsonArray.toString();
		return result;
    }
    
    public static String getJSONStr(String retCode,Object result){
    	Map<String,Object> map = new HashMap<String, Object>();
    	map.put("retCode", retCode);
    	map.put("result", result);
    	map.put("retMessage", RetCodeDef.retCodeMap.get(retCode));
    	return JSON.toJSONString(map);
    }
    
	public static RespMessage getResp(String retCode,Object result){
		RespMessage respMessage = new RespMessage();
		respMessage.setResult(result);
		respMessage.setRetCode(retCode);
		respMessage.setRetMessage(RetCodeDef.retCodeMap.get(retCode));
		return respMessage;
	}
    
}
